package com.idlecode.config.query;

import cn.hutool.core.util.StrUtil;
import com.idlecode.config.DbType;

/**
 * MariaDb查询
 */
public class MariaDbQuery implements AbstractQuery {

    @Override
    public DbType dbType() {
        return DbType.MariaDb;
    }

    @Override
    public String dbNamesSql() {
        return "SELECT schema_name AS OWNER FROM information_schema.SCHEMATA ORDER BY schema_name";
    }

    @Override
    public String tableSql(String dataBaseName, String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append("select table_name, table_comment from information_schema.tables ");
        sql.append("where table_schema = ");
        //数据库查询
        if (StrUtil.isNotBlank(dataBaseName)) {
            sql.append("'").append(dataBaseName).append("' ");
        } else {
            sql.append("(SELECT DATABASE()) ");
        }
        // 表名查询
        if (StrUtil.isNotBlank(tableName)) {
            sql.append("and table_name = '").append(tableName).append("' ");
        }
        sql.append("order by table_name asc");

        return sql.toString();
    }

    @Override
    public String dbName() {
        return "OWNER";
    }

    @Override
    public String tableName() {
        return "table_name";
    }

    @Override
    public String tableComment() {
        return "table_comment";
    }

    @Override
    public String tableUpdateTime() {
        return "update_time";
    }

    @Override
    public String tableFieldsSql(String dataBaseName, String tableName) {
        return StrUtil.format("select\n" +
                "  column_name,\n" +
                "  data_type,\n" +
                "  column_comment,\n" +
                "  numeric_precision,\n" +
                "  numeric_scale,\n" +
                "  column_key,\n" +
                "  is_nullable,\n" +
                "  character_maximum_length\n" +
                "from\n" +
                "  information_schema.columns\n" +
                "where\n" +
                "  table_schema = '{}'\n" +
                "  and table_name = '{}'\n" +
                "order by\n" +
                "  ordinal_position", dataBaseName, tableName);
    }

    @Override
    public String fieldName() {
        return "column_name";
    }

    @Override
    public String fieldType() {
        return "data_type";
    }

    @Override
    public String fieldComment() {
        return "column_comment";
    }

    @Override
    public String fieldKey() {
        return "column_key";
    }

    @Override
    public String dataPrecision() {
        return "numeric_precision";
    }

    @Override
    public String dataScale() {
        return "numeric_scale";
    }

    @Override
    public String isNullable() {
        return "is_nullable";
    }

    @Override
    public String characterMaximumLength() {
        return "character_maximum_length";
    }
}
